package start.gui.audio;

import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;

import javax.sound.sampled.*;
import javax.swing.SwingWorker;

public class Playback extends SwingWorker<Void,Void>{
	
	private String filename;
	
	public Playback(String filename){
		this.filename = filename;
	}


	@Override
	protected Void doInBackground()  throws IOException, UnsupportedAudioFileException{
		
		AudioInputStream audioStream = AudioSystem.getAudioInputStream(new File(filename));
		try{
				AudioFormat formatoAudio=audioStream.getFormat();

				SourceDataLine sourceDataLine=null;
				DataLine.Info info=new DataLine.Info(SourceDataLine.class,formatoAudio);

				try{
					sourceDataLine=(SourceDataLine)AudioSystem.getLine(info);
					sourceDataLine.open();
				}catch(LineUnavailableException e){
					e.printStackTrace();
				}

				sourceDataLine.start();

				int nBytesToRead=0;
				byte[] buffer=new byte[1024];
				while(nBytesToRead!=-1){
					nBytesToRead=audioStream.read(buffer,0,buffer.length);

					if(nBytesToRead>0){
						sourceDataLine.write(buffer, 0,nBytesToRead);
					}
				}

				sourceDataLine.drain();
				sourceDataLine.close();
			}catch(IOException e){
				e.printStackTrace();
			}
			
			return null;
		
	}


	/*public static void main(String[] args){
		Playback play = new Playback();
		try {
			play.play("sounds/lock.wav");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (UnsupportedAudioFileException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		System.exit(0); 
	}*/

/*
	@Override
	protected Void doInBackground() throws Exception {
		// TODO Auto-generated method stub
		return null;
	}*/


}
